package com.example.yilanchatserver.business.freechat.service.impl;

import com.example.yilanchatserver.business.freechat.OpenAISubscriber;
import com.example.yilanchatserver.business.freechat.OpenAiWebClient;
import com.example.yilanchatserver.business.freechat.service.ChatGPTService;
import com.example.yilanchatserver.business.freechat.service.dto.FreeChatDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;


@Service
@RequiredArgsConstructor
@Slf4j
public class ChatGPTServiceImpl implements ChatGPTService {


    private final OpenAiWebClient openAiWebClient;




    @Override
    public Flux<String> send(FreeChatDTO chatDTO) {


//        Message userMessage = new Message(MessageType.TEXT, UserType.USER, content);
//        int currentToken = (int) (content.length() / TOKEN_CONVERSION_RATE);
//        List<Message> history = userSessionUtil.getHistory(sessionId, MessageType.TEXT, (int) ((MAX_TOKEN / TOKEN_CONVERSION_RATE) - currentToken));
//        log.info("history:{}", history);
//        String historyDialogue = history.stream().map(e -> String.format(e.getUserType().getCode(), e.getMessage())).collect(Collectors.joining());

//        String prompt = StringUtils.hasLength(historyDialogue) ? String.format("%sQ:%s\nA: ", historyDialogue, content) : content;


        return Flux.create(emitter -> {
            OpenAISubscriber subscriber = new OpenAISubscriber(emitter);
            Flux<String> openAiResponse =
                    openAiWebClient.getChatResponse(chatDTO.getRobotId(), chatDTO.getTalkList(), null, null, null);
            openAiResponse.subscribe(subscriber);
            emitter.onDispose(subscriber);
        });
    }
}
